package com.nai365.nart.search.service.impl;

import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.nai365.nart.common.core.constant.SecurityConstants;
import com.nai365.nart.common.core.es.SkuEsModel;
import com.nai365.nart.common.core.es.SpuEsModel;
import com.nai365.nart.common.core.to.SkuHasStockTO;
import com.nai365.nart.common.core.util.R;
import com.nai365.nart.search.config.NartElasticSearchConfig;
import com.nai365.nart.search.constant.EsConstant;
import com.nai365.nart.search.feign.ProductFeignService;
import com.nai365.nart.search.service.MallSearchService;
import com.nai365.nart.search.vo.SearchParam;
import com.nai365.nart.search.vo.SearchResult;
import com.nai365.nart.search.vo.SearchSkuParam;
import com.nai365.nart.search.vo.SearchSkuResult;
import com.nai365.nart.ware.api.feign.WareFeignService;
import lombok.extern.slf4j.Slf4j;
import org.checkerframework.checker.units.qual.min;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.*;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.aggregations.metrics.*;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.collapse.CollapseBuilder;
import org.elasticsearch.search.sort.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import static com.nai365.nart.search.constant.EsConstant.PRODUCT_INDEX;
import static com.nai365.nart.search.constant.EsConstant.SKU_INDEX;
import static java.awt.SystemColor.menu;


/**
 * @Description:
 * @Created: with IntelliJ IDEA.
 * @author: baogs
 * @createTime: 2021-03-13 14:19
 **/

@Slf4j
@Service
public class MallSearchServiceImpl implements MallSearchService {

	@Autowired
	private RestHighLevelClient esRestClient;

	@Resource
	private ProductFeignService productFeignService;
	@Resource
	private WareFeignService wareFeignService ;

	@Override
	public SearchResult search(SearchParam param) {

		//1、动态构建出查询需要的DSL语句
		SearchResult result = null;

		//1、准备检索请求
		SearchRequest searchRequest = buildSearchRequest(param);

		try {
			//2、执行检索请求
			SearchResponse response = esRestClient.search(searchRequest, NartElasticSearchConfig.COMMON_OPTIONS);

			//3、分析响应数据，封装成我们需要的格式
			result = buildSearchResult(response, param);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}

	@Override
	public SearchSkuResult searchSku(SearchSkuParam param) {

		//1、动态构建出查询需要的DSL语句
		SearchSkuResult result = null;

		//1、准备检索请求
		SearchRequest searchRequest = buildSearchSkuRequest(param);

		try {
			//2、执行检索请求
			SearchResponse response = esRestClient.search(searchRequest, NartElasticSearchConfig.COMMON_OPTIONS);

			Aggregation skus = response.getAggregations().get("skus");
			Aggregation spuId = response.getAggregations().get("spuId");
			Integer type = param.getType();
			if (type != null && type == 2) {
				result = new SearchSkuResult();
				if (param.getSpuIds() !=null && param.getSpuIds().size() >0){
					result.setStats(spuId);
				} else {
					result.setStats(skus);
				}
				return result;
			}

			//3、分析响应数据，封装成我们需要的格式
			result = buildSearchSkuResult(response, param);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;
	}


	/**
	 * 构建结果数据
	 * 模糊匹配，过滤（按照属性、分类、品牌，价格区间，库存），完成排序、分页、高亮,聚合分析功能
	 *
	 * @param response
	 * @return
	 */
	private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {

		SearchResult result = new SearchResult();

		//1、返回的所有查询到的商品
		SearchHits hits = response.getHits();

		List<SpuEsModel> esModels = new ArrayList<>();
		//遍历所有商品信息
		if (hits.getHits() != null && hits.getHits().length > 0) {
			for (SearchHit hit : hits.getHits()) {
				String sourceAsString = hit.getSourceAsString();
				SpuEsModel esModel = JSON.parseObject(sourceAsString, SpuEsModel.class);

				esModels.add(esModel);
			}
		}
		result.setProduct(esModels);

		//2、当前商品涉及到的所有属性信息
		List<SearchResult.AttrVo> attrVos = new ArrayList<>();
		//获取属性信息的聚合
		ParsedNested attrsAgg = response.getAggregations().get("attr_agg");
		if (attrsAgg != null) {
			ParsedStringTerms attrIdAgg = attrsAgg.getAggregations().get("attr_id_agg");
			for (Terms.Bucket bucket : attrIdAgg.getBuckets()) {
				SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
				//1、得到属性的id
				long attrId = bucket.getKeyAsNumber().longValue();
				attrVo.setAttrId(attrId);


				//3、得到属性的所有值
				ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
				List<String> attrValues = attrValueAgg.getBuckets().stream().map(item -> item.getKeyAsString()).collect(Collectors.toList());
				attrVo.setAttrValue(attrValues);

				attrVos.add(attrVo);
			}
		}
		result.setAttrs(attrVos);

		//3、当前商品涉及到的所有品牌信息
		List<SearchResult.BrandVo> brandVos = new ArrayList<>();
		//获取到品牌的聚合
		ParsedLongTerms brandAgg = response.getAggregations().get("brand_agg");
		for (Terms.Bucket bucket : brandAgg.getBuckets()) {
			SearchResult.BrandVo brandVo = new SearchResult.BrandVo();

			//1、得到品牌的id
			long brandId = bucket.getKeyAsNumber().longValue();
			brandVo.setBrandId(brandId);


			brandVos.add(brandVo);
		}
		result.setBrands(brandVos);

		//4、当前商品涉及到的所有分类信息
		//获取到分类的聚合
		List<SearchResult.CatalogVo> catalogVos = new ArrayList<>();
		ParsedLongTerms catalogAgg = response.getAggregations().get("catalog_agg");
		for (Terms.Bucket bucket : catalogAgg.getBuckets()) {
			SearchResult.CatalogVo catalogVo = new SearchResult.CatalogVo();
			//得到分类id
			String keyAsString = bucket.getKeyAsString();
			catalogVo.setCatalogId(Long.parseLong(keyAsString));

			//得到分类名
//            ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
//            String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
//            catalogVo.setCatalogName(catalogName);
			catalogVos.add(catalogVo);
		}

		result.setCatalogs(catalogVos);
		//===============以上可以从聚合信息中获取====================//
		//5、分页信息-页码
		result.setPageNum(param.getCurrent());
		//5、1分页信息、总记录数
//        long total = hits.getTotalHits().value;
		Cardinality cardinality = response.getAggregations().get("total");
		long total = cardinality.getValue();

		result.setTotal(total);

		//5、2分页信息-总页码-计算
		int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ?
				(int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
		result.setTotalPages(totalPages);

		List<Integer> pageNavs = new ArrayList<>();
		for (int i = 1; i <= totalPages; i++) {
			pageNavs.add(i);
		}
		result.setPageNavs(pageNavs);

		return result;
	}

	/**
	 * 构建结果数据
	 * 模糊匹配，过滤（按照属性、分类、品牌，价格区间，库存），完成排序、分页、高亮,聚合分析功能
	 *
	 * @param response
	 * @return
	 */
	private SearchSkuResult buildSearchSkuResult(SearchResponse response, SearchSkuParam param) {

		SearchSkuResult result = new SearchSkuResult();

		//1、返回的所有查询到的商品
		SearchHits hits = response.getHits();

		List<SkuEsModel> esModels = new ArrayList<>();
		//遍历所有商品信息
		if (hits.getHits() != null && hits.getHits().length > 0) {
			for (SearchHit hit : hits.getHits()) {
				String sourceAsString = hit.getSourceAsString();
				SkuEsModel esModel = JSON.parseObject(sourceAsString, SkuEsModel.class);

				esModels.add(esModel);
			}
		}

		if(param.getSpuId() != null &&param.getType() != null && param.getType() == 1) {
			List<Long> ids = esModels.parallelStream().map(item -> item.getSkuId()).collect(Collectors.toList());
			R skuHasStock = wareFeignService.getSkuHasStockInner(ids, SecurityConstants.FROM_IN);
			if (skuHasStock.getCode() == 0 && skuHasStock.getData() != null) {
				List<SkuHasStockTO> skuHasStockTOs = JSONUtil.toList(JSONUtil.toJsonStr(skuHasStock.getData()), SkuHasStockTO.class);
				Map<Long, SkuHasStockTO> collect = skuHasStockTOs.parallelStream().collect(Collectors.toMap(SkuHasStockTO::getSkuId, Function.identity()));
				esModels = esModels.parallelStream().map(item ->
				{
					item.setHasStock(collect.get(item.getSkuId()).getHasStock());
					return item;
				}).collect(Collectors.toList());

			}
		}

		//处理排序
		Stream<SkuEsModel> sorted = null;
		if (!StringUtils.isEmpty(param.getSort())) {
			String sort = param.getSort();
			String[] sortFileds = sort.split("_");

			if ("asc".equals(sortFileds[1]) && "updateTime".equals(sortFileds[0])) {

				sorted = esModels.parallelStream().sorted(Comparator.comparing(SkuEsModel::getUpdateTime));
			} else if ("desc".equals(sortFileds[1]) && "updateTime".equals(sortFileds[0])) {
				sorted = esModels.parallelStream().sorted(Comparator.comparing(SkuEsModel::getUpdateTime).reversed());
			} else if ("asc".equals(sortFileds[1]) && "skuPrice".equals(sortFileds[0])) {

				sorted = esModels.parallelStream().sorted(Comparator.comparing(SkuEsModel::getPrice));
			} else if ("desc".equals(sortFileds[1]) && "skuPrice".equals(sortFileds[0])) {
				sorted = esModels.parallelStream().sorted(Comparator.comparing(SkuEsModel::getPrice).reversed());
			}
		}
		if (sorted != null) {
			List<SkuEsModel> collect = sorted.collect(Collectors.toList());
			result.setProduct(collect);
		} else {
			result.setProduct(esModels);
		}


		//===============以上可以从聚合信息中获取====================//
		//5、分页信息-页码
		result.setPageNum(param.getCurrent());
		//5、1分页信息、总记录数
        long total = hits.getTotalHits().value;
//		Cardinality cardinality = response.getAggregations().get("total");
//		long total = cardinality.getValue();

		result.setTotal(total);

		//5、2分页信息-总页码-计算
		int totalPages = (int) total % EsConstant.PRODUCT_PAGESIZE == 0 ?
				(int) total / EsConstant.PRODUCT_PAGESIZE : ((int) total / EsConstant.PRODUCT_PAGESIZE + 1);
		result.setTotalPages(totalPages);

		List<Integer> pageNavs = new ArrayList<>();
		for (int i = 1; i <= totalPages; i++) {
			pageNavs.add(i);
		}
		result.setPageNavs(pageNavs);

		return result;
	}


	/**
	 * 准备检索请求
	 * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
	 *
	 * @return
	 */
	private SearchRequest buildSearchRequest(SearchParam param) {

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

		/**
		 * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
		 */
		//1. 构建bool-query
		BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();

		//1.1 bool-must
		if (!StringUtils.isEmpty(param.getKeyword())) {
			boolQueryBuilder.must(QueryBuilders.matchQuery("spuName", param.getKeyword()))
					.should(QueryBuilders.matchQuery("brandName", param.getKeyword()));
		}


		//1.2 bool-fiter
		//1.2.1 catelogId
		if (null != param.getCatalog3Id()) {
			try {
				R r = productFeignService.selectChildIdByCatId(param.getCatalog3Id().intValue(), SecurityConstants.FROM_IN);
				List<Long> data = (List<Long>) r.getData(r.getData().toString(), new TypeReference<List<Long>>() {
				});
				boolQueryBuilder.filter(QueryBuilders.termsQuery("catalogId", data));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
//        if(null != param.getType()){
//        	if ("0".equals(param.getType())){
//				boolQueryBuilder.filter(QueryBuilders.termsQuery("type",param.getType()));
//			}else {
//				boolQueryBuilder.filter(QueryBuilders.termsQuery("type", param.getType(), "0"));
//			}
//        }

		//1.2.2 brandId
		if (null != param.getBrandId() && param.getBrandId().size() > 0) {
			boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
		}

		//1.2.2 brandId
		if (null != param.getBrandId() && param.getBrandId().size() > 0) {
			boolQueryBuilder.filter(QueryBuilders.termsQuery("brandId", param.getBrandId()));
		}


		//1.2.5 skuPrice
		if (!StringUtils.isEmpty(param.getSkuPrice())) {
			//skuPrice形式为：1_500或_500或500_
			RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("skuPrice");
			String[] price = param.getSkuPrice().split("_");
			if (price.length == 2) {
				rangeQueryBuilder.gte(price[0]).lte(price[1]);
			} else if (price.length == 1) {
				if (param.getSkuPrice().startsWith("_")) {
					rangeQueryBuilder.lte(price[1]);
				}
				if (param.getSkuPrice().endsWith("_")) {
					rangeQueryBuilder.gte(price[0]);
				}
			}
			boolQueryBuilder.filter(rangeQueryBuilder);
		}

		//封装所有的查询条件
		searchSourceBuilder.query(boolQueryBuilder);

		//根据spuId去重，spuId相同只返回一条
		CollapseBuilder collapseBuilder = new CollapseBuilder("id");
		searchSourceBuilder.collapse(collapseBuilder);


		/**
		 * 排序，分页，高亮
		 */

		//排序
		//形式为sort=hotScore_asc/desc
		if (!StringUtils.isEmpty(param.getSort())) {
			String sort = param.getSort();
			String[] sortFileds = sort.split("_");

			SortOrder sortOrder = "asc".equalsIgnoreCase(sortFileds[1]) ? SortOrder.ASC : SortOrder.DESC;

			searchSourceBuilder.sort(sortFileds[0], sortOrder);
		} else {
			searchSourceBuilder.sort("saleTime", SortOrder.DESC);
		}

		//分页
		searchSourceBuilder.from((param.getCurrent() - 1) * EsConstant.PRODUCT_PAGESIZE);
		searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);


		/**
		 * 聚合分析
		 */
		//1. 按照品牌进行聚合
		TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
		brand_agg.field("brandId").size(50);


		AggregationBuilder aggregation = AggregationBuilders.cardinality("total").field("spuId");
		searchSourceBuilder.aggregation(aggregation);

		searchSourceBuilder.aggregation(brand_agg);

		//2. 按照分类信息进行聚合
		TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
		catalog_agg.field("catalogId").size(20);

//        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

		searchSourceBuilder.aggregation(catalog_agg);


		log.debug("构建的DSL语句 {}", searchSourceBuilder.toString());

		SearchRequest searchRequest = new SearchRequest(new String[]{PRODUCT_INDEX}, searchSourceBuilder);

		return searchRequest;
	}


	/**
	 * 准备检索请求
	 * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存），排序，分页，高亮，聚合分析
	 *
	 * @return
	 */
	private SearchRequest buildSearchSkuRequest(SearchSkuParam param) {

		SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();

		/**
		 * 模糊匹配，过滤（按照属性，分类，品牌，价格区间，库存）
		 */
		//1. 构建bool-query
		BoolQueryBuilder boolQueryBuilder = new BoolQueryBuilder();



		//1.1 bool-must
		if (!StringUtils.isEmpty(param.getKeyword())) {
			boolQueryBuilder.must(QueryBuilders.matchQuery("skuName", param.getKeyword()))
					.should(QueryBuilders.matchQuery("brandName", param.getKeyword()));
		}


		//1.2 bool-fiter
		//1.2.1 catelogId
		if (null != param.getCatalog3Id()) {
			try {
				R r = productFeignService.selectChildIdByCatId(param.getCatalog3Id().intValue(), SecurityConstants.FROM_IN);
				List<Long> data = (List<Long>) r.getData(r.getData().toString(), new TypeReference<List<Long>>() {
				});
				boolQueryBuilder.filter(QueryBuilders.termsQuery("catalogId", data));
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		//根据spuId去重，spuId相同只返回一条
		Integer type = param.getType();
		if (type != null && type == 0 || type == null) {
			CollapseBuilder collapseBuilder = new CollapseBuilder("spuId");
			searchSourceBuilder.collapse(collapseBuilder);
			searchSourceBuilder.sort("price", SortOrder.ASC);
		} else if (type != null && type == 1 &&  param.getSpuId() != null) {
			boolQueryBuilder.filter(QueryBuilders.termQuery("spuId", param.getSpuId()));
		} else if(type != null && type == 2
				&& (param.getSpuId() != null
				|| (param.getSpuIds() !=null && param.getSpuIds().size() >0))){
			if (param.getSpuId() != null) {
				//根据spuId 统计价格相关最大，平均，最小等
				boolQueryBuilder.filter(QueryBuilders.termQuery("spuId", param.getSpuId()));
				searchSourceBuilder.aggregation(AggregationBuilders.stats("skus").field("price"));
			} else if (param.getSpuIds() !=null && param.getSpuIds().size() >0){
				//根据spuId 分组统计价格品均值
				boolQueryBuilder.filter(QueryBuilders.termsQuery("spuId", param.getSpuIds()));
				TermsAggregationBuilder field = AggregationBuilders.terms("spuId").field("spuId");
				AvgAggregationBuilder price = AggregationBuilders.avg("price").field("price");
				field.subAggregation(price);
				searchSourceBuilder.aggregation(field);
			}

		}

		//1.2.2 brandId
		if (null != param.getBrandId() ) {
			boolQueryBuilder.filter(QueryBuilders.termQuery("brandId", param.getBrandId()));
		}
		if (null != param.getSkuId()) {
			boolQueryBuilder.filter(QueryBuilders.termQuery("skuId", param.getSkuId()));
		}
		Long ownerId = param.getOwnerId();
		if (ownerId != null){
			boolQueryBuilder.filter(QueryBuilders.termQuery("ownerId", param.getOwnerId()));
		}


		//1.2.5 skuPrice
		if (!StringUtils.isEmpty(param.getSkuPrice())) {
			//skuPrice形式为：1_500或_500或500_
			RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("price");
			String[] price = param.getSkuPrice().split("_");
			if (price.length == 2) {
				rangeQueryBuilder.gte(price[0]).lte(price[1]);
			} else if (price.length == 1) {
				if (param.getSkuPrice().startsWith("_")) {
					rangeQueryBuilder.lte(price[1]);
				}
				if (param.getSkuPrice().endsWith("_")) {
					rangeQueryBuilder.gte(price[0]);
				}
			}
			boolQueryBuilder.filter(rangeQueryBuilder);
		}
		if (!StringUtils.isEmpty(param.getCreateTime())) {
			//skuPrice形式为：1_500或_500或500_
			RangeQueryBuilder rangeQueryBuilder = QueryBuilders.rangeQuery("createTime");
			String[] createTime = param.getCreateTime().split("_");
			if (createTime.length == 2) {
				rangeQueryBuilder.gte(createTime[0]).lte(createTime[1]);
			} else if (createTime.length == 1) {
				if (param.getSkuPrice().startsWith("_")) {
					rangeQueryBuilder.lte(createTime[1]);
				}
				if (param.getSkuPrice().endsWith("_")) {
					rangeQueryBuilder.gte(createTime[0]);
				}
			}
			boolQueryBuilder.filter(rangeQueryBuilder);
		}

		//封装所有的查询条件
		searchSourceBuilder.query(boolQueryBuilder);


		/**
		 * 排序，分页，高亮
		 */

		//排序
		//形式为sort=hotScore_asc/desc
//		List<SortBuilder> sortBuilders = new ArrayList<>();
//		if(!StringUtils.isEmpty(param.getSort())){
//			String sort = param.getSort();
//			String[] sortFileds = sort.split("_");

//			SortOrder sortOrder="asc".equalsIgnoreCase(sortFileds[1])?SortOrder.ASC:SortOrder.DESC;
//			searchSourceBuilder.sort(sortFileds[0],sortOrder);
//			searchSourceBuilder.sort("price",SortOrder.ASC);

//			NestedSortBuilder nestedSortBuilder = new NestedSortBuilder(sortFileds[0]);
//			FieldSortBuilder order = SortBuilders.fieldSort("price").order(SortOrder.ASC);
//			FieldSortBuilder order1 = SortBuilders.fieldSort("price").order(SortOrder.ASC);
//			sortBuilders.add(order);
//			sortBuilders.add(order1);
//			TopHitsAggregationBuilder top = AggregationBuilders.topHits("top");
//			TermsAggregationBuilder field1 = AggregationBuilders.terms("one").field("spuId")
//			TopHitsAggregationBuilder top = AggregationBuilders.topHits("top");
//			top.sort("price",SortOrder.ASC);
//			field1.subAggregation(top);
//			searchSourceBuilder.aggregation(field1);
//			searchSourceBuilder.sort("price",SortOrder.ASC);
//			searchSourceBuilder.sort(sortFileds[0],sortOrder);
//			top.size(100);
//			searchSourceBuilder.sort("price",SortOrder.ASC);
//			searchSourceBuilder.sort(sortFileds[0],sortOrder);
//			searchSourceBuilder.aggregation(top);
//			searchSourceBuilder.sort(order1);
//			searchSourceBuilder.sort("sortPrice", SortOrder.ASC);


//
//		} else {
//			searchSourceBuilder.sort("sortPrice", SortOrder.ASC);
//		}



		//分页
		searchSourceBuilder.from((param.getCurrent() - 1) * EsConstant.PRODUCT_PAGESIZE);
		searchSourceBuilder.size(EsConstant.PRODUCT_PAGESIZE);


		/**
		 * 聚合分析
		 */
		//1. 按照品牌进行聚合
//		TermsAggregationBuilder brand_agg = AggregationBuilders.terms("brand_agg");
//		brand_agg.field("brandId").size(50);
//
//
		AggregationBuilder aggregation = AggregationBuilders.cardinality("total").field("spuId");
		searchSourceBuilder.aggregation(aggregation);

//		searchSourceBuilder.aggregation(brand_agg);
//
//		//2. 按照分类信息进行聚合
//		TermsAggregationBuilder catalog_agg = AggregationBuilders.terms("catalog_agg");
//		catalog_agg.field("catalogId").size(20);

//        catalog_agg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(1));

//		searchSourceBuilder.aggregation(catalog_agg);


		log.debug("构建的DSL语句 {}", searchSourceBuilder.toString());

		SearchRequest searchRequest = new SearchRequest(new String[]{SKU_INDEX}, searchSourceBuilder);

		return searchRequest;
	}
}
